package com.kobe.game_40;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * 
 * 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
 * 
 * Find the sum of all numbers which are equal to the sum of the factorial of
 * their digits.
 * 
 * Note: as 1! = 1 and 2! = 2 are not sums they are not included.
 * 
 * 
 */
public class Game34 {

    static List<Integer> factorials = new ArrayList<Integer>();

    public static int getFactorial(int number) {
        int result = 1;
        for (int i = 2; i <= number; i++) {
            result *= i;
        }
        return result;
    }

    static {
        for (int i = 0; i <= 9; i++) {
            factorials.add(getFactorial(i));
        }
    }

    public static int[] numberToArray(int number) {
        int[] result = new int[7];
        for (int i = 0; i < 7; i++) {
            result[6 - i] = number % 10;
            number = number / 10;
        }

        return result;
    }

    // max is 7-digital
    // max number is below 999999
    public static void main(String[] args) {
        int[] tempArray ;
        int temp;
        int result;
        List<Integer> resultList = new ArrayList<Integer>();
        boolean begin = false;
        loop:for (int i = 145; i < 999999; i++) {
            tempArray = numberToArray(i);
            result = 0;
            begin = false;
            for (int j = 0;j<7;j++){
                if (tempArray[j] != 0 && !begin){
                    begin = true;
                }if (begin){
                    temp = factorials.get(tempArray[j]);
                    if (temp>i){
                        continue loop;
                    }else{
                        result += temp;
                    }
                    if (result == i){
                        System.out.println(i);
                        resultList.add(i);
                    }
                }
            }
        }
        
        int finalResult = 0;
        for(int tempResult:resultList){
            finalResult += tempResult;
        }
        System.out.println(finalResult);
    }

}
